import { logger } from '../utils/logger';
import prisma from '../lib/prisma';
import axios from 'axios';
import { Submission } from '@prisma/client';

interface LearningProgress {
  studentId: string;
  subject: string;
  scores: number[];
  weakPoints: string[];
  strongPoints: string[];
  learningHabits?: {
    studyTime: number;
    practiceFrequency: number;
    errorRate: number;
  };
}

interface RecommendationResult {
  personalizedPlan: {
    focusAreas: string[];
    suggestedTopics: string[];
    practiceStrategy: string;
    timeAllocation: Record<string, number>;
  };
  learningResources: Array<{
    type: string;
    title: string;
    description: string;
    difficulty: string;
    url?: string;
  }>;
  exerciseRecommendations: Array<{
    type: string;
    count: number;
    difficulty: string;
    topics: string[];
  }>;
  improvementSuggestions: string[];
}

export class AIRecommendationService {
  private static readonly API_ENDPOINT = process.env.AI_RECOMMENDATION_API_URL;
  private static readonly API_KEY = process.env.AI_RECOMMENDATION_API_KEY;

  // 获取个性化学习建议
  static async getPersonalizedRecommendations(
    studentId: string,
    subject: string
  ): Promise<RecommendationResult> {
    try {
      // 获取学生学习进度数据
      const progress = await this.getLearningProgress(studentId, subject);

      // 调用AI服务生成建议
      const response = await axios.post<RecommendationResult>(
        this.API_ENDPOINT as string,
        {
          progress,
          subject
        },
        {
          headers: {
            'Authorization': `Bearer ${this.API_KEY}`,
            'Content-Type': 'application/json'
          }
        }
      );

      const recommendations = response.data;

      // 保存建议记录
      await this.saveRecommendationRecord(studentId, subject, recommendations);

      logger.info('生成个性化建议成功', {
        studentId,
        subject
      });

      return recommendations;
    } catch (error) {
      logger.error('生成个性化建议失败', { error, studentId, subject });
      throw new Error('生成个性化建议失败，请稍后再试');
    }
  }

  // 获取基于知识图谱的学习路径建议
  static async getLearningPathRecommendations(
    studentId: string,
    subject: string,
    targetTopic: string
  ): Promise<RecommendationResult> {
    try {
      // 获取学生当前掌握的知识点
      const masteredPoints = await this.getMasteredKnowledgePoints(studentId, subject);

      // 调用AI服务生成学习路径
      const response = await axios.post<RecommendationResult>(
        `${this.API_ENDPOINT}/learning-path` as string,
        {
          studentId,
          subject,
          targetTopic,
          masteredPoints
        },
        {
          headers: {
            'Authorization': `Bearer ${this.API_KEY}`,
            'Content-Type': 'application/json'
          }
        }
      );

      const recommendations = response.data;

      // 保存学习路径记录
      await this.saveLearningPathRecord(studentId, subject, targetTopic, recommendations);

      logger.info('生成学习路径建议成功', {
        studentId,
        subject,
        targetTopic
      });

      return recommendations;
    } catch (error) {
      logger.error('生成学习路径建议失败', { error, studentId, subject, targetTopic });
      throw new Error('生成学习路径建议失败，请稍后再试');
    }
  }

  // 获取学习进度数据
  private static async getLearningProgress(
    studentId: string,
    subject: string
  ): Promise<LearningProgress> {
    // 获取最近的考试成绩
    const scores = await prisma.submission.findMany({
      where: {
        userId: studentId,
        question: {
          subject
        }
      },
      orderBy: {
        createdAt: 'desc'
      },
      select: {
        score: true
      },
      take: 10
    });

    // 分析弱项知识点
    const weakPoints = await this.analyzeWeakPoints(studentId, subject);

    // 分析强项知识点
    const strongPoints = await this.analyzeStrongPoints(studentId, subject);

    // 获取学习习惯数据
    const learningHabits = await this.getLearningHabits(studentId);

    return {
      studentId,
      subject,
      scores: scores.map((s: { score: number }) => s.score),
      weakPoints,
      strongPoints,
      learningHabits
    };
  }

  // 分析弱项知识点
  private static async analyzeWeakPoints(
    studentId: string,
    subject: string
  ): Promise<string[]> {
    const weakPoints = await prisma.$queryRaw`
      WITH student_scores AS (
        SELECT
          q."knowledgePoint",
          AVG(s.score) as avg_score
        FROM "Submission" s
        JOIN "Question" q ON q.id = s."questionId"
        WHERE s."userId" = ${studentId}
        AND q.subject = ${subject}
        GROUP BY q."knowledgePoint"
      )
      SELECT "knowledgePoint"
      FROM student_scores
      WHERE avg_score < 70
      ORDER BY avg_score ASC
      LIMIT 5
    `;

    return weakPoints.map((wp: any) => wp.knowledgePoint);
  }

  // 分析强项知识点
  private static async analyzeStrongPoints(
    studentId: string,
    subject: string
  ): Promise<string[]> {
    const strongPoints = await prisma.$queryRaw`
      WITH student_scores AS (
        SELECT
          q."knowledgePoint",
          AVG(s.score) as avg_score
        FROM "Submission" s
        JOIN "Question" q ON q.id = s."questionId"
        WHERE s."userId" = ${studentId}
        AND q.subject = ${subject}
        GROUP BY q."knowledgePoint"
      )
      SELECT "knowledgePoint"
      FROM student_scores
      WHERE avg_score >= 85
      ORDER BY avg_score DESC
      LIMIT 5
    `;

    return strongPoints.map((sp: any) => sp.knowledgePoint);
  }

  // 获取学习习惯数据
  private static async getLearningHabits(studentId: string) {
    // 计算平均学习时间
    const studyTimeStats = await prisma.studyRecord.aggregate({
      where: {
        studentId,
        createdAt: {
          gte: new Date(Date.now() - 30 * 24 * 60 * 60 * 1000) // 最近30天
        }
      },
      _avg: {
        duration: true
      },
      _count: {
        id: true
      }
    });

    // 计算练习频率（每周平均练习次数）
    const practiceFrequency = studyTimeStats._count.id / 4; // 除以4周

    // 计算错误率
    const submissions = await prisma.submission.findMany({
      where: {
        userId: studentId,
        createdAt: {
          gte: new Date(Date.now() - 30 * 24 * 60 * 60 * 1000)
        }
      },
      select: {
        score: true
      }
    });

    const errorRate = submissions.filter((s: Submission) => s.score < 60).length / submissions.length;

    return {
      studyTime: studyTimeStats._avg.duration || 0,
      practiceFrequency,
      errorRate
    };
  }

  // 保存建议记录
  private static async saveRecommendationRecord(
    studentId: string,
    subject: string,
    recommendations: RecommendationResult
  ) {
    await prisma.recommendationRecord.create({
      data: {
        studentId,
        subject,
        recommendations: recommendations as any,
        type: 'PERSONALIZED',
        status: 'ACTIVE'
      }
    });
  }

  // 保存学习路径记录
  private static async saveLearningPathRecord(
    studentId: string,
    subject: string,
    targetTopic: string,
    recommendations: RecommendationResult
  ) {
    await prisma.recommendationRecord.create({
      data: {
        studentId,
        subject,
        targetTopic,
        recommendations: recommendations as any,
        type: 'LEARNING_PATH',
        status: 'ACTIVE'
      }
    });
  }

  // 获取已掌握的知识点
  private static async getMasteredKnowledgePoints(
    studentId: string,
    subject: string
  ): Promise<string[]> {
    const masteredPoints = await prisma.$queryRaw`
      WITH knowledge_scores AS (
        SELECT
          q."knowledgePoint",
          AVG(s.score) as avg_score,
          COUNT(*) as attempt_count
        FROM "Submission" s
        JOIN "Question" q ON q.id = s."questionId"
        WHERE s."userId" = ${studentId}
        AND q.subject = ${subject}
        GROUP BY q."knowledgePoint"
      )
      SELECT "knowledgePoint"
      FROM knowledge_scores
      WHERE avg_score >= 80
      AND attempt_count >= 3
    `;

    return masteredPoints.map((mp: any) => mp.knowledgePoint);
  }
}
